/*
 * 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.idock.frame.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import cn.idock.frame.PzApplication;
import cn.idock.frame.R;
import cn.idock.frame.adapter.DownloadJobAdapter;
import cn.idock.frame.download.DownloadJob;
import cn.idock.frame.download.DownloadManager;
import cn.idock.frame.download.DownloadObserver;

/**
 * @author idock
 */
public class DownloadActivity extends Activity implements DownloadObserver {

	/**
	 * Runnable periodically querying DownloadService about downloads
	 */
	private Runnable mUpdateTimeTask = new Runnable() {
		public void run() {
			updateListView(0);
		}
	};

	private Handler mHandler;

	private ListView mListView;

	private DownloadManager mDownloadManager;

	/**
	 * Launch this Activity from the outside
	 * 
	 * @param c
	 *            context from which Activity should be started
	 */
	public static void launch(Context c) {
		Intent intent = new Intent(c, DownloadActivity.class);
		c.startActivity(intent);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.download);

		mDownloadManager = PzApplication.getInstance().getDownloadManager();

		mListView = (ListView) findViewById(R.id.DownloadListView);

		mHandler = new Handler();

		registerForContextMenu(mListView);
	}

	@Override
	protected void onPause() {
		mHandler.removeCallbacks(mUpdateTimeTask);
		mDownloadManager.deregisterDownloadObserver(this);
		super.onPause();
	}

	@Override
	protected void onResume() {
		mDownloadManager.registerDownloadObserver(this);
		updateListView(0);
		super.onResume();
	}

	private int lastSpinnerPosition = -1;

	private void updateListView(int position) {
		ArrayList<DownloadJob> jobs = null;
		switch (position) {
		case 0:
			// Display ALL
			jobs = mDownloadManager.getAllDownloads();
			break;

		case 1:
			// Display Completed
			jobs = mDownloadManager.getCompletedDownloads();
			break;

		case 2:
			// Display Queued
			jobs = mDownloadManager.getQueuedDownloads();
			break;

		default:
			break;
		}

		DownloadJobAdapter adapter = (DownloadJobAdapter) mListView.getAdapter();

		if (lastSpinnerPosition == position && jobs != null && jobs.size() == adapter.getCount()) {
			adapter.notifyDataSetChanged();
			return;
		} else {
			adapter = new DownloadJobAdapter(DownloadActivity.this);
			adapter.setList(jobs);
			mListView.setAdapter(adapter);
		}
		lastSpinnerPosition = position;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		if (v.getId() == R.id.DownloadListView) {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.download_context, menu);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.delete_download:
			deleteJob(getJob(info.position));
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	private void deleteJob(DownloadJob job) {
		mDownloadManager.deleteDownload(job);
		DownloadJobAdapter adapter = (DownloadJobAdapter) mListView.getAdapter();
		adapter.notifyDataSetChanged();
	}

	private DownloadJob getJob(int position) {
		return (DownloadJob) mListView.getAdapter().getItem(position);
	}

	@Override
	public void onDownloadChanged(DownloadManager manager) {
		mHandler.post(mUpdateTimeTask);
	}
}
